from marshmallow import fields
from webutils.tornado.web import RequestHandler
from webutils.tornado.responses import Response
from webutils.webargs.tornado import use_args

from .. import params, services


class TextMessageHandler(RequestHandler):
    @use_args(
        {
            'token': params.Token(required=True),
            'chat_id': fields.Int(required=False, missing=0),
            'offset': fields.Int(required=False, missing=20),
        },
        location='query')
    async def get(self, args, room_id=None):
        chat_service = services.ChatService(self.connection, room_id=room_id)
        total = await chat_service.get_text_message_count()
        start = args['chat_id']
        end = start + args['offset']
        lst = await chat_service.get_text_message_lst(start, end)
        data = {'total': total, 'list': lst}
        resp = Response(errcode=0, errmsg='ok', data=data)
        self.write_response(resp)


class ImageMessageHandler(RequestHandler):
    @use_args(
        {
            'token': params.Token(required=True),
            'chat_id': fields.Int(required=False, missing=0),
            'offset': fields.Int(required=False, missing=20),
        },
        location='query')
    async def get(self, args, room_id=None):
        chat_service = services.ChatService(self.connection, room_id=room_id)
        total = await chat_service.get_image_message_count()
        start = args['chat_id']
        end = start + args['offset']
        lst = await chat_service.get_image_message_lst(start, end)
        data = {'total': total, 'list': lst}
        resp = Response(errcode=0, errmsg='ok', data=data)
        self.write_response(resp)
